<template>
  <el-dialog
    center
    v-if="isShow"
    v-dialogDrag
    :title="title"
    v-loading="loading"
    :width="dialogWidth"
    :before-close="close"
    :visible.sync="isShow"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-position="right"
      class="overflow pl15 pr15"
    >
      <el-row type="flex" justify="space-around">
        <el-col :span="24" class="mb15 form-inp">
          <el-form-item
            label="公寓名称："
            prop="name"
            :label-width="labelWidth"
            class="required"
          >
            <el-input
              class="floor"
              v-model="form.name"
              autocomplete="off"
              placeholder="请输入公寓名称"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row type="flex" justify="space-around">
        <el-col :span="24" class="mb15">
          <el-form-item
            label="详情描述："
            prop="content"
            :label-width="labelWidth"
            class="required"
          >
            <RichText :filesObject="filesObject"></RichText>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row type="flex" justify="center">
        <el-col :span="24" class="mb15">
          <el-form-item
            label="图片："
            :label-width="labelWidth"
            class="required"
          >
            <Thumbnail
              @deleteUserAvatar="handleDeleteUserAvatar"
              :photos="photoArr"
            ></Thumbnail>
            <ImageUpload
              :pegs="pegs"
              :limit="limit"
              :imageMaxSize="imageMaxSize"
              @uploadFiles="handleUploadFiles"
            ></ImageUpload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer align-center tiling inline-block">
      <el-button @click="close">取 消</el-button>
      <el-button class="theme-btn" @click="handleConfirm('form')"
        >保 存</el-button
      >
    </span>
  </el-dialog>
</template>

<script>
import "@/utils/drag.js";
import RichText from "@/components/rich_text";
import Thumbnail from "@/components/thumbnail";
import ImageUpload from "@/components/image_upload";
import { vName, vlength } from "@/utils/verification.js";
import { addApartment, editApartment } from "@/apis/business";

export default {
  name: "Apartment_dialog",
  data() {
    return {
      form: {
        name: "",
        content: ""
      },
      limit: 1,
      pegs: [],
      photoArr: [],
      filesObject: {},
      imageMaxSize: 1024,
      labelWidth: "125px",
      dialogWidth: "980px",
      rules: {
        name: {
          validator: vName(2, 8, "请输入公寓名称"),
          trigger: "blur"
        }
      }
    };
  },
  computed: {
    isShow() {
      return this.addDialog || this.editDialog;
    }
  },
  mounted() {
    tinymce.init({});
  },
  watch: {
    async editDialog() {
      if (this.editDialog) {
        this.form = {
          name: this.apartmentForm.name,
          photo: this.apartmentForm.photos,
          content: this.apartmentForm.content
        };

        this.photoArr = [this.form.photo];
        this.pegs = JSON.parse(JSON.stringify(this.photoArr));
      }
    },
    addDialog() {
      this.addDialog && this.resetForm();
    }
  },
  methods: {
    handleUploadFiles(props) {
      this.uploadFileList = props;
    },
    handleConfirm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.editDialog ? this.editApartment() : this.addApartment();
        }
      });
    },
    addApartment() {
      const formData = new FormData();
      const newContent = tinyMCE.activeEditor.getContent();

      const file = this.uploadFileList.length && this.uploadFileList[0];

      if (!this.uploadFileList.length && !this.pegs.length) {
        return this.$notify.error({
          title: "错误",
          message: "请先上传广告图片！"
        });
      }

      if (file) {
        formData.append("file", file.raw);
      }

      formData.append("content", newContent);
      formData.append("name", this.form.name);

      this.$store.dispatch("load/setLoading", true);
      // addApartment(formData).then(res => {
      //   if (res && res.code === "200") {
      //     this.$emit("update");
      //     this.$emit("close");
      //     this.$notify({
      //       title: res.msg,
      //       type: "success"
      //     });
      //   }
      // });
      this.$emit("update");
      this.$emit("close");
      this.$notify({
        title: "操作成功！",
        type: "success"
      });
    },
    handleDeleteUserAvatar(delUrl) {
      this.photoArr.forEach((item, index) => {
        if (item === delUrl) {
          this.photoArr[index] = `D${item}`;
          this.pegs = this.pegs.filter(item => item !== delUrl);
        }
      });
    },
    editApartment() {
      const formData = new FormData();

      const file = this.uploadFileList && this.uploadFileList[0];
      const newContent = tinyMCE.activeEditor.getContent();

      if (
        !this.uploadFileList ||
        (!this.uploadFileList.length && !this.pegs.length)
      ) {
        return this.$notify.error({
          title: "错误",
          message: "请先上传广告图片！"
        });
      }

      if (file) {
        formData.append("file", file.raw);
      }

      formData.append("content", newContent);
      formData.append("name", this.form.name);
      formData.append("id", this.apartmentForm.id);

      this.$store.dispatch("load/setLoading", true);
      // editApartment(formData).then(res => {
      //   if (res && res.code === "200") {
      //     this.$emit("update");
      //     this.$emit("close");
      //     this.$notify({
      //       title: res.msg,
      //       type: "success"
      //     });
      //   }
      // });
      this.$emit("update");
      this.$emit("close");
      this.$notify({
        title: "操作成功！",
        type: "success"
      });
    },
    close() {
      this.$emit("close");
      this.resetForm();
    },
    resetForm() {
      this.form = {
        name: "",
        content: ""
      };
      this.photoArr = [];
      this.uploadFileList = [];
    }
  },
  components: {
    Thumbnail,
    ImageUpload,
    RichText
  },
  props: ["addDialog", "editDialog", "title", "apartmentForm", "loading"]
};
</script>

<style scoped></style>
